package com.cike.sparkstudy.core.java;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.broadcast.Broadcast;

import java.util.Arrays;
import java.util.List;

public class BroadcastVariable {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf().setAppName("BroadcastVariable").setMaster("local");

        JavaSparkContext sc = new JavaSparkContext(conf);

        //Broadcast变量实现一个节点只有一个Broadcast变量，实现多个Task共享一个变量
        //创建BroadCast变量需要调用broadcast()方法进行创建。
        final int factor = 3;
        final Broadcast<Integer> factorBroadcast = sc.broadcast(factor);

        List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6);
        JavaRDD<Integer> numbers = sc.parallelize(numberList);

        //把RDD中的每个元素都*广播变量
        JavaRDD<Integer> multipleNumbers = numbers.map(new Function<Integer, Integer>() {
            private static final long serialVersionUID = 8274901796546989645L;

            @Override
            public Integer call(Integer v1) throws Exception {
                int factor = factorBroadcast.value();
                return v1 * factor;
            }
        });

        multipleNumbers.foreach(new VoidFunction<Integer>() {
            @Override
            public void call(Integer t) throws Exception {
                System.out.println(t);
            }
        });

        sc.close();

    }
}
